package com.i2863.recnews.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.i2863.recnews.common.Constant;
import com.i2863.recnews.domain.Admin;
import com.i2863.recnews.exception.LoginException;
import com.i2863.recnews.util.HttpSessionUtils;
import com.i2863.recnews.util.MD5Utils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xuweiwei on 2017/5/18.
 */
@Service("adminService")
public class AdminService {

    CloseableHttpClient httpClient = HttpSessionUtils.buildHttpClient();

    public Admin getUserByName(String username, String password) {
        Map<String,String> paramMap = new HashMap<String,String>();
        try {
            paramMap.put("method","login");
            paramMap.put("username",username);
            paramMap.put("password", MD5Utils.encrypt(password));
            paramMap.put("siteId","65");
            String json = HttpSessionUtils.httpPost(httpClient, Constant.UCENTER_URL,paramMap);
            JSONObject jsonObject = JSON.parseObject(json);
            int code = jsonObject.getInteger("code");
            if(code!=0){
                throw new LoginException(jsonObject.getString("message"));
            }

            //登录成功,查找id
            Map<String,String> param2 = new HashMap<String,String>();
            param2.put("method","getUserInfo");
            param2.put("username",username);
            param2.put("siteId","56");
            String json2 = HttpSessionUtils.httpPost(httpClient,Constant.UCENTER_URL,param2);
            JSONObject jsonObject2 = JSON.parseObject(json2);
            int code2 = jsonObject2.getInteger("code");
            if(code2!=0){
                throw new LoginException(jsonObject2.getString("message"));
            }
            Integer siteId = jsonObject2.getJSONObject("data").getInteger("siteId");
            String nickName = jsonObject2.getJSONObject("data").getString("nickName");
            String logo = jsonObject2.getJSONObject("data").getString("logo");
            Admin  admin = new Admin();
            admin.setUsername(username);
            admin.setSiteId(siteId);
            admin.setNickName(nickName);
            admin.setLogo(logo);
            return admin;

        } catch (IOException e) {
           throw new LoginException("系统错误");
        }
    }

    public static void main(String[] args) {
        new AdminService().getUserByName("13980974244","123456");
    }
}
